﻿using System.Security.Cryptography;
using System.Text;

namespace ZHDJ.MobileInterface
{
    public sealed class TripleDES
    {
        public static string Encrypt(string plainString, string cryptographyKey, string cryptographyIV)
        {
            byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(plainString);

            TripleDESCryptoServiceProvider tripleCryptoProvider = new TripleDESCryptoServiceProvider();
            byte[] destKeyBytes = new byte[24];
            System.Array.Copy(UTF8Encoding.UTF8.GetBytes(cryptographyKey), 0, destKeyBytes, 0, 24);
            tripleCryptoProvider.Key = destKeyBytes;

            byte[] destIVBytes = new byte[8];
            System.Array.Copy(UTF8Encoding.UTF8.GetBytes(cryptographyIV), 0, destIVBytes, 0, 8);
            tripleCryptoProvider.IV = destIVBytes;

            tripleCryptoProvider.Mode = CipherMode.CBC;
            tripleCryptoProvider.Padding = PaddingMode.PKCS7;

            ICryptoTransform cryptoTransform = tripleCryptoProvider.CreateEncryptor();
            byte[] resultArray = cryptoTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
            tripleCryptoProvider.Clear();
            return System.Convert.ToBase64String(resultArray, 0, resultArray.Length);
        }

        public static string Decrypt(string encryptedString, string cryptographyKey, string cryptographyIV)
        {
            byte[] toDecryptArray = System.Convert.FromBase64String(encryptedString);

            TripleDESCryptoServiceProvider tripleCryptoProvider = new TripleDESCryptoServiceProvider();
            byte[] destKeyBytes = new byte[24];
            System.Array.Copy(UTF8Encoding.UTF8.GetBytes(cryptographyKey), 0, destKeyBytes, 0, 24);
            tripleCryptoProvider.Key = destKeyBytes;

            byte[] destIVBytes = new byte[8];
            System.Array.Copy(UTF8Encoding.UTF8.GetBytes(cryptographyIV), 0, destIVBytes, 0, 8);
            tripleCryptoProvider.IV = destIVBytes;

            tripleCryptoProvider.Mode = CipherMode.CBC;
            tripleCryptoProvider.Padding = PaddingMode.PKCS7;

            ICryptoTransform cryptoTransform = tripleCryptoProvider.CreateDecryptor();
            byte[] resultArray = cryptoTransform.TransformFinalBlock(toDecryptArray, 0, toDecryptArray.Length);
            tripleCryptoProvider.Clear();
            return UTF8Encoding.UTF8.GetString(resultArray);
        }
    }
}